import React from 'react'
import { Card, Button, Checkbox, Form, Input, message } from 'antd'
import { observer } from 'mobx-react'
import logo from '@/assets/logo.png'
import './index.scss'
import useStore from '@/store'
import { useNavigate } from 'react-router-dom'

const Login = () => {
  const { storeLogin } = useStore()
  const navigate = useNavigate()
  // 登录
  const onFinish = async (values) => {
    try {
      await storeLogin.login(values)
      navigate('/')
    } catch (err) {
      message.error('登录失败')
    }
  }

  // 是否同意协议的自定义校验
  const isAgree = (rule, val) =>
    val ? Promise.resolve() : Promise.reject(new Error('请同意勾选'))

  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          validateTrigger={['onChange', 'onBlur']}
          initialValues={{
            mobile: '13911111111',
            code: '246810',
            agree: false
          }}
          onFinish={onFinish}
        >
          {/* 账号 */}
          <Form.Item
            name="mobile"
            rules={[
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号码格式不对'
              },
              { required: true, message: '请输入手机号' }
            ]}
          >
            <Input size="large" placeholder="请输入手机号" />
          </Form.Item>
          {/* 验证码 */}
          <Form.Item
            name="code"
            rules={[
              {
                len: 6,
                message: '密码长度6位'
              },
              { required: true, message: '请输入验证码' }
            ]}
          >
            <Input.Password size="large" placeholder="请输入验证码" />
          </Form.Item>
          <Form.Item
            name="agree"
            valuePropName="checked"
            rules={[
              {
                validator: isAgree
              }
            ]}
          >
            <Checkbox className="login-checkbox-label">
              我已阅读并同意「用户协议」和「隐私条款」
            </Checkbox>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" size="large" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default observer(Login)
